require('dotenv').config();
const mongoose = require('mongoose');
const CampusNotice = require('./src/models/CampusNotice');
const HotTopic = require('./src/models/HotTopic');
const Activity = require('./src/models/Activity');
const MarketItem = require('./src/models/MarketItem');

const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');

// 创建images目录
const imagesDir = path.join(__dirname, 'images');
if (!fs.existsSync(imagesDir)) {
  fs.mkdirSync(imagesDir);
}

async function convertImageUrl(url) {
  try {
    // 下载图片
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const buffer = await response.buffer();
    
    // 写入到本地文件（可选）
    const fileName = path.basename(url).replace(/[?*:|"<>\s]/g, '_');
    const filePath = path.join(imagesDir, fileName);
    fs.writeFileSync(filePath, buffer);
    
    // 转换为base64
    const base64Image = buffer.toString('base64');
    
    return base64Image;
  } catch (error) {
    console.error('图片下载或转换失败：', error.message);
    return null; // 返回null或默认值
  }
}

async function initFullData() {
  try {
    // 连接数据库
    await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/mongodb');
    console.log('MongoDB连接成功');

    // 清空现有数据
    await Promise.all([
      CampusNotice.deleteMany({}),
      HotTopic.deleteMany({}),
      Activity.deleteMany({}),
      MarketItem.deleteMany({})
    ]);
    console.log('已清空现有数据');

    // 校园通知数据（完整）
    const notices = [
      {
        title: '关于图书馆闭馆整理的通知',
        content: '因图书盘点与整理工作，本周五图书馆闭馆一天，后续开放时间不变，望周知。',
        category: 'facility',
        date: new Date('2023-10-15'),
        type: '图书馆通知',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Notice+01')
      },
      {
        title: '校园网络维护通知',
        content: '今晚23:00 - 次日6:00将进行校园网络设备维护，期间网络可能中断，敬请谅解。',
        category: 'facility',
        date: new Date('2023-10-14'),
        type: '网络服务',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Notice+02')
      },
      {
        title: '学生疫苗接种安排',
        content: '下周一起，分批次组织学生进行流感疫苗接种，具体批次请关注班级群通知。',
        category: 'health',
        date: new Date('2023-10-16'),
        type: '医疗健康',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Notice+03')
      },
      {
        title: '教学楼电梯检修通知',
        content: '教学楼A栋电梯将于明后两天进行安全检修，期间请走楼梯，给您带来不便请谅解。',
        category: 'facility',
        date: new Date('2023-10-13'),
        type: '后勤保障',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Notice+04')
      },
      {
        title: '校园招聘会预告',
        content: '本月底将举办校园综合招聘会，涵盖多个热门行业，欢迎毕业生提前准备简历。',
        category: 'career',
        date: new Date('2023-10-17'),
        type: '就业服务',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Notice+05')
      },
      {
        title: '食堂菜品更新通知',
        content: '食堂本周新增特色窗口，推出地方风味美食，欢迎师生前往品尝并反馈意见。',
        category: 'dining',
        date: new Date('2023-10-12'),
        type: '餐饮服务',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Notice+06')
      },
      {
        title: '校园安全检查通知',
        content: '本周三将开展校园安全大检查，重点检查宿舍违规电器、消防设施等，望配合。',
        category: 'safety',
        date: new Date('2023-10-18'),
        type: '安全管理',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Notice+07')
      },
      {
        title: '社团活动场地调整',
        content: '因大型活动筹备，部分社团活动场地临时调整至体育馆副馆，具体见社团群通知。',
        category: 'organization',
        date: new Date('2023-10-11'),
        type: '社团管理',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Notice+08')
      },
      {
        title: '教材发放补充通知',
        content: '部分专业教材已到货，未领取的同学请于本周内前往教材科登记领取，逾期不候。',
        category: 'academic',
        date: new Date('2023-10-10'),
        type: '教学服务',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Notice+09')
      },
      {
        title: '校园志愿者招募',
        content: '学校组织社区服务志愿活动，需招募若干同学，报名请至学生会办公室填写表格。',
        category: 'other',
        date: new Date('2023-10-19'),
        type: '志愿服务',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Notice+10')
      }
    ];

    // 热门话题数据（完整）
    const topics = [
      {
        title: '校园运动场馆开放时间调整讨论',
        content: '大家觉得运动场馆开放时间是否合理？晚上能否延长至22点？来聊聊你的想法！',
        count: 126,
        tags: ['校园设施', '运动', '意见征集'],
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Topic+01')
      },
      {
        title: '期末复习计划分享',
        content: '临近期末，有没有高效的复习计划？欢迎分享各科复习技巧和时间安排~',
        count: 98,
        tags: ['学习', '期末', '经验交流'],
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Topic+02')
      },
      {
        title: '校园食堂新菜品吐槽与建议',
        content: '食堂新出的菜品大家觉得咋样？有哪些改进意见？一起说说让食堂更美味！',
        count: 153,
        tags: ['校园生活', '餐饮', '反馈'],
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Topic+03')
      },
      {
        title: '校园文创产品创意征集',
        content: '想设计属于我们校园的文创产品，比如书签、笔记本等，大家有啥好创意？',
        count: 85,
        tags: ['校园文化', '创意', '文创'],
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Topic+04')
      },
      {
        title: '考研自习室座位分配探讨',
        content: '考研自习室座位紧张，怎样分配更公平合理？是按申请时间还是轮流使用？',
        count: 112,
        tags: ['学习', '考研', '自习室'],
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Topic+05')
      },
      {
        title: '校园音乐节表演曲目推荐',
        content: '校园音乐节要来了，大家希望听到哪些歌曲？经典老歌还是流行热曲？',
        count: 79,
        tags: ['校园活动', '音乐', '推荐'],
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Topic+06')
      },
      {
        title: '校园共享单车管理问题',
        content: '共享单车乱停乱放影响校园环境，该如何规范管理？大家出出主意！',
        count: 134,
        tags: ['校园设施', '管理', '共享单车'],
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Topic+07')
      },
      {
        title: '暑期实践活动经验交流',
        content: '参加暑期实践的同学，来分享下你的收获和故事，给学弟学妹们点参考~',
        count: 67,
        tags: ['实践', '暑期', '经验'],
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Topic+08')
      },
      {
        title: '校园社团招新宣传创意',
        content: '社团招新季，怎样宣传才能吸引更多同学加入？海报、短视频还是线下活动？',
        count: 92,
        tags: ['社团', '招新', '创意'],
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Topic+09')
      },
      {
        title: '校园周边美食探店分享',
        content: '发现校园周边好吃的小店了吗？不管是小吃还是正餐，快来推荐给大家！',
        count: 105,
        tags: ['校园生活', '美食', '探店'],
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Topic+10')
      }
    ];

    // 活动数据（完整）
    const activities = [
      {
        title: '春季运动会',
        description: '包含短跑、跳远、拔河等多个项目，欢迎师生组队报名，展现青春活力。',
        startTime: new Date('2023-10-25T09:00:00'),
        endTime: new Date('2023-10-25T17:00:00'),
        location: '学校体育场',
        category: 'sports',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Activity+01')
      },
      {
        title: '学术讲座周',
        description: '邀请多位行业专家，开展计算机、金融、文学等领域的学术讲座，拓宽视野。',
        startTime: new Date('2023-11-01T14:00:00'),
        endTime: new Date('2023-11-05T16:00:00'),
        location: '学术报告厅',
        category: 'academic',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Activity+02')
      },
      {
        title: '社团嘉年华',
        description: '各社团展示特色活动，有精彩表演、互动游戏，还有社团招新，不容错过。',
        startTime: new Date('2023-10-28T10:00:00'),
        endTime: new Date('2023-10-28T18:00:00'),
        location: '体育馆广场',
        category: 'culture',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Activity+03')
      },
      {
        title: '毕业生交流会',
        description: '邀请优秀毕业生分享求职、考研经验，为在校同学答疑解惑，助力职业规划。',
        startTime: new Date('2023-11-05T09:00:00'),
        endTime: new Date('2023-11-05T15:00:00'),
        location: '教学楼阶梯教室',
        category: 'career',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Activity+04')
      },
      {
        title: '校园开放日',
        description: '面向家长和社会开放，展示校园风貌、教学成果，欢迎参观交流。',
        startTime: new Date('2023-11-12T09:00:00'),
        endTime: new Date('2023-11-12T16:00:00'),
        location: '校园各区域',
        category: 'culture',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Activity+05')
      },
      {
        title: '校园文化节',
        description: '涵盖书法、绘画、摄影展览，以及戏剧、朗诵表演，展现校园文化魅力。',
        startTime: new Date('2023-11-18T10:00:00'),
        endTime: new Date('2023-11-18T20:00:00'),
        location: '艺术楼展厅及礼堂',
        category: 'culture',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Activity+06')
      },
      {
        title: '趣味运动会',
        description: '设置接力障碍赛、两人三足等趣味项目，强调团队协作，欢迎师生参与。',
        startTime: new Date('2023-10-30T14:00:00'),
        endTime: new Date('2023-10-30T17:00:00'),
        location: '体育场副场',
        category: 'sports',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Activity+07')
      },
      {
        title: '创业分享会',
        description: '邀请创业成功校友分享经历，讲解创业流程、融资技巧，为有想法的同学助力。',
        startTime: new Date('2023-11-08T15:00:00'),
        endTime: new Date('2023-11-08T17:00:00'),
        location: '创新创业中心',
        category: 'career',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Activity+08')
      },
      {
        title: '校园音乐会',
        description: '校内音乐社团和个人带来精彩演出，涵盖流行、古典等多种曲风，享受音乐盛宴。',
        startTime: new Date('2023-11-20T19:00:00'),
        endTime: new Date('2023-11-20T21:00:00'),
        location: '体育馆',
        category: 'culture',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Activity+09')
      },
      {
        title: '志愿者服务日',
        description: '组织校园及社区志愿服务活动，如校园清洁、敬老服务等，传递爱心。',
        startTime: new Date('2023-10-22T09:00:00'),
        endTime: new Date('2023-10-22T16:00:00'),
        location: '校园及周边社区',
        category: 'other',
        cover: await convertImageUrl('https://picsum.photos/200/150?text=Activity+10')
      }
    ];

    // 二手市场数据（完整）
    const marketItems = [
      {
        title: '出九成新笔记本电脑',
        description: '配置i5处理器、8G内存、256G固态，使用两年，无维修记录，适合日常办公学习。',
        price: 2800,
        category: 'digital',
        condition: 'good',
        images: ['/images/market1.jpg'],
        contact: '微信：campus_flea01'
      },
      {
        title: '转让考研复习资料',
        description: '包含数学、英语、政治各科历年真题、笔记，2024考研适用，几乎全新。',
        price: 80,
        category: 'books',
        condition: 'like_new',
        images: ['/images/market2.jpg'],
        contact: 'QQ：123456789'
      },
      {
        title: '出闲置山地自行车',
        description: '铝合金车架，24速变速，刹车灵敏，带车锁和水壶架，骑行轻松。',
        price: 600,
        category: 'transportation',
        condition: 'good',
        images: [await convertImageUrl('https://picsum.photos/200/150?text=Flea+03')],
        contact: '电话：138xxxx1234'
      },
      {
        title: '卖女式冬装大衣',
        description: '中长款，黑色呢子面料，M码，版型修身，保暖性好，仅穿过几次。',
        price: 150,
        category: 'clothing',
        condition: 'like_new',
        images: [await convertImageUrl('https://picsum.photos/200/150?text=Flea+04')],
        contact: '微信：flea_cloth04'
      },
      {
        title: '出二手游戏键盘',
        description: '机械青轴，全键无冲，背光可调，适合游戏玩家，外观九成新。',
        price: 200,
        category: 'digital_accessories',
        condition: 'good',
        images: [await convertImageUrl('https://picsum.photos/200/150?text=Flea+05')],
        contact: 'QQ：987654321'
      },
      {
        title: '转让健身器材（哑铃）',
        description: '一对10公斤哑铃，铸铁材质，配有防滑垫，适合宿舍健身使用。',
        price: 50,
        category: 'sports_equipment',
        condition: 'good',
        images: [await convertImageUrl('https://picsum.photos/200/150?text=Flea+06')],
        contact: '微信：campus_fitness06'
      },
      {
        title: '卖闲置专业摄影三脚架',
        description: '碳纤维材质，轻便易携带，承重稳定，适合摄影爱好者，几乎全新。',
        price: 300,
        category: 'photography_equipment',
        condition: 'like_new',
        images: [await convertImageUrl('https://picsum.photos/200/150?text=Flea+07')],
        contact: '电话：159xxxx5678'
      },
      {
        title: '出大学教材（汉语言文学）',
        description: '多本汉语言文学专业教材，如古代文学、现代汉语等，价格可议，适合低年级同学。',
        price: '每本 10 - 20 元',
        category: 'books',
        condition: 'good',
        images: [await convertImageUrl('https://picsum.photos/200/150?text=Flea+08')],
        contact: '微信：flea_books08'
      },
      {
        title: '转让无线降噪耳机',
        description: '品牌型号 XXX，降噪效果好，续航持久，音质清晰，使用半年，无损坏。',
        price: 400,
        category: 'digital',
        condition: 'good',
        images: [await convertImageUrl('https://picsum.photos/200/150?text=Flea+09')],
        contact: 'QQ：234567890'
      },
      {
        title: '卖闲置厨房小电器（电煮锅）',
        description: '多功能电煮锅，可煮面、炒菜、蒸蛋，适合宿舍使用，功率小不跳闸。',
        price: 30,
        category: 'household_appliances',
        condition: 'good',
        images: [await convertImageUrl('https://picsum.photos/200/150?text=Flea+10')],
        contact: '微信：campus_life010'
      }
    ];

    // 插入数据
    console.log('开始插入数据...');
    
    await Promise.all([
      CampusNotice.insertMany(notices),
      HotTopic.insertMany(topics),
      Activity.insertMany(activities),
      MarketItem.insertMany(marketItems)
    ]);

    console.log('数据初始化成功！');
  } catch (error) {
    console.error('数据初始化失败：', error);
  } finally {
    await mongoose.disconnect();
    console.log('MongoDB连接已关闭');
    process.exit(0);
  }
}

// 运行初始化函数
initFullData();